package com.example.user_module;

import androidx.room.Room;

import com.blankj.utilcode.util.LogUtils;
import com.example.base_application.BaseApplication;
import com.example.common.mvvm.BaseEntity;
import com.example.common.mvvm.model.BaseRepository;
import com.example.network_sdk.RetrofitManager;
import com.example.user_module.dao.UserDataBase;
import com.example.user_module.dao.UserEntity;
import com.example.user_module.login.UserInfoEntity;
import com.google.gson.Gson;

import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class UserRepository extends BaseRepository {
    public Observable<BaseEntity>queryUser(){
        UserDataBase db = Room.databaseBuilder(BaseApplication.getInstance(),
                UserDataBase.class, "user.db").build();
        Maybe<List<UserEntity>> maybe = db.userDao().queryUser();
        Observable<BaseEntity> queryUserEntityObservable = maybe.flatMapObservable(new Function<List<UserEntity>, ObservableSource<? extends BaseEntity>>() {
            @Override
            public ObservableSource<? extends BaseEntity> apply(@NonNull List<UserEntity> userEntities) throws Exception {
                UserEntity entity = new UserEntity();
                entity.status=200;
                if (userEntities==null){
                    entity.message="用户未登录";
                    Observable<UserEntity>userEntityObservable = Observable.just(entity);
                    return functionObservable(userEntityObservable);
                }
                if (userEntities.size() == 0){
                    entity.message="用户未登录";
                    Observable<UserEntity>userEntityObservable = Observable.just(entity);
                    return functionObservable(userEntityObservable);
                }
                entity.message="用户已登录";
                entity = userEntities.get(userEntities.size()-1);
                Gson gson = new Gson();
                String s = gson.toJson(userEntities.get(userEntities.size()-1));
                LogUtils.e("entity"+s);
                LogUtils.e("entity"+entity.message);
                Observable<UserEntity>userEntityObservable = Observable.just(entity);
                return functionObservable(userEntityObservable);
            }
        });
        return queryUserEntityObservable;
    }

    public Observable<BaseEntity>requestQueryUser(long userId){
        Observable<UserInfoEntity> userEntityObservable = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).requestQuery( userId);
        return userEntityObservable.map(new Function<UserInfoEntity, BaseEntity>() {
            @Override
            public BaseEntity apply(@NonNull UserInfoEntity userInfoEntity) throws Exception {
                return userInfoEntity;
            }
        });
    }
}
